﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace LdCms.Web.Controllers.MVC.Community
{
    using LdCms.EF.DbModels;
    using LdCms.Web.Authorizes;
    using LdCms.IBLL.Community;
    using LdCms.Common.Extension;
    using LdCms.Common.Utility;
    using LdCms.Common.Web;
    using LdCms.Web.Models;
    using LdCms.Web.Services;
    using LdCms.Common.Json;

    /// <summary>
    /// 
    /// </summary>
    [AdminAuthorizeAttribute(Roles = "Admins")]
    public class CommunityThemeController : BaseController
    {
        private readonly IBaseManager BaseManager;
        private readonly IColumnService ColumnService;
        private readonly IThemeService ThemeService;
        private readonly IThemeContentService ThemeContentService;
        private readonly IVThemeService VThemeService;
        public CommunityThemeController(IBaseManager BaseManager, IColumnService ColumnService, IThemeService ThemeService, IThemeContentService ThemeContentService, IVThemeService VThemeService) : base(BaseManager)
        {
            this.BaseManager = BaseManager;
            this.ColumnService = ColumnService;
            this.ThemeService = ThemeService;
            this.ThemeContentService = ThemeContentService;
            this.VThemeService = VThemeService;
        }
        public override IActionResult Index()
        {
            return View();
        }

        public IActionResult List()
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.列表);
                if (!IsPermission(funcId)) { return ToPermission(funcId); }

                string startTime = GetQueryString("datemin");
                string endTime = GetQueryString("datemax");
                string columnId = GetQueryString("columnId");
                string top = GetQueryString("top");
                string wonderful = GetQueryString("wonderful");
                string state = GetQueryString("state");
                string keyword = GetQueryString("keyword");
                ViewData["DateMin"] = startTime;
                ViewData["DateMax"] = endTime;
                ViewData["ColumnId"] = columnId;
                ViewData["Top"] = top;
                ViewData["Wonderful"] = wonderful;
                ViewData["State"] = state;
                ViewData["Keyword"] = keyword;

                int total = 100;
                List<Ld_Community_Theme> lists = new List<Ld_Community_Theme>();
                string strKeyword = string.Format("{0}{1}{2}{3}{4}{5}", startTime, columnId, top, wonderful, state, keyword);
                if (string.IsNullOrWhiteSpace(strKeyword))
                    lists = ThemeService.GetThemeTop(SystemID, CompanyID, total);
                else
                    lists = ThemeService.SearchTheme(SystemID, CompanyID, startTime, endTime, columnId, top, wonderful, state, keyword, total);
                ViewData["Count"] = ThemeService.CountTheme(SystemID, CompanyID);
                return View(lists);
            }
            catch (Exception ex)
            {
                return ToError(ex.Message);
            }
        }
        public IActionResult Add(string themeId)
        {
            try
            {
                string funcId = string.Empty;
                if (!IsAddPermission(themeId, out funcId)) { return ToPermission(funcId); }

                if (string.IsNullOrWhiteSpace(themeId))
                    return View(new V_Community_Theme());
                var entity = VThemeService.GetTheme(SystemID, CompanyID, themeId);
                if (entity == null)
                    return View(new V_Community_Theme());
                return View(entity);
            }
            catch (Exception ex)
            {
                return ToError(ex.Message);
            }
        }


        [HttpPost]
        public JsonResult Save(string themeId)
        {
            try
            {
                string funcId = string.Empty;
                if (!IsSavePermission(themeId)) { return Error("您没有操作权限，请联系系统管理员！"); }

                string fTitle = GetFormValue("fTitle");
                string fColumnId = GetFormValue("fColumnId");
                string fColumnName = GetFormValue("fColumnName");
                string fImgSrc = GetFormValue("fImgSrc");
                string fImgArray = GetFormValueArr("fImgArray[]");
                string fHits = GetFormValue("fHits");
                string fKeyword = GetFormValue("fKeyword");
                string fDescription = GetFormValue("fDescription");
                string fContent = GetFormValue("fContent");
                string fIsWonderful = GetFormValue("fIsWonderful");
                string fIsTop = GetFormValue("fIsTop");
                string fIsLock = GetFormValue("fIsLock");
                string fState = GetFormValue("fState");

                if (string.IsNullOrWhiteSpace(fTitle))
                    return Error("标题不能为空！");
                if (string.IsNullOrWhiteSpace(fContent))
                    return Error("内容不能为空！");
                if (string.IsNullOrWhiteSpace(fImgSrc) && !string.IsNullOrWhiteSpace(fImgArray))
                    fImgSrc = fImgArray.Split(",")[0];

                string imgArray = string.IsNullOrWhiteSpace(fImgArray) ? "" : fImgArray.Split(",").ToJson();
                string keyword = string.IsNullOrWhiteSpace(fKeyword) ? WebHelper.NoHtml(Utility.ContentDecode(fContent)).Left(100) : fKeyword;
                string description = string.IsNullOrWhiteSpace(fDescription) ? WebHelper.NoHtml(Utility.ContentDecode(fContent)).Left(100) : fDescription;

                var entity = ThemeService.GetTheme(SystemID, CompanyID, themeId);
                var content = ThemeContentService.GetThemeContent(SystemID, CompanyID, themeId);
                entity.Title = fTitle;
                entity.ColumnID = fColumnId;
                entity.ColumnName = fColumnName;
                entity.ImgSrc = fImgSrc;
                entity.ImgArray = imgArray;
                entity.Hits = fHits.ToInt();
                entity.IsWonderful = fIsWonderful.ToBool();
                entity.IsTop = fIsTop.ToBool();
                entity.IsLock = fIsLock.ToBool();
                entity.State = fState.ToBool();
                content.Keyword = keyword;
                content.Description = description;
                content.Content = fContent;
                bool result = ThemeService.UpdateTheme(entity, content);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult UpdateState(string themeId, bool state)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.审核);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }

                var result = ThemeService.UpdateThemeState(SystemID, CompanyID, themeId, state);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult Delete(string themeId)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.栏目管理.栏目分类.删除);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }

                var result = ThemeService.DeleteTheme(SystemID, CompanyID, themeId);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult DeleteBatch(string[] arrId)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.删除);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }

                if (arrId.Length == 0)
                    return Error("请选择删除ID!");
                List<object> lists = new List<object>();
                foreach (var item in arrId)
                {
                    string themeId = item;
                    try
                    {
                        bool result = ThemeService.DeleteTheme(SystemID, CompanyID, themeId);
                        lists.Add(new { themeid = themeId, result, message = "ok" });
                    }
                    catch (Exception ex)
                    {
                        lists.Add(new { themeid = themeId, result = false, message = ex.Message });
                    }
                }
                return Success("成功！", lists);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }


        #region 辅助方法
        [HttpGet]
        [ActionName("column-list-all")]
        public JsonResult GetColumnAll()
        {
            try
            {
                var lists = ColumnService.GetColumnAll(SystemID, CompanyID);
                if (lists == null)
                    return Error("not data！");
                var data = from m in lists
                           select new
                           {
                               id = m.ColumnID,
                               name = m.ColumnName
                           };
                return Success("ok", data);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion


        #region 私有化方法
        public bool IsSavePermission(string noticeId)
        {
            try
            {

                if (string.IsNullOrWhiteSpace(noticeId))
                {
                    string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.新增);
                    return IsPermission(funcId) ? true : false;
                }
                else
                {
                    string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.编辑);
                    return IsPermission(funcId) ? true : false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public bool IsAddPermission(string noticeId, out string funcId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(noticeId))
                {
                    funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.新增);
                    return IsPermission(funcId) ? true : false;
                }
                else
                {
                    funcId = PermissionEnum.CodeFormat((int)PermissionEnum.公告管理.公告信息.编辑);
                    return IsPermission(funcId) ? true : false;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion


    }
}